<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="70%"
    :close-on-click-modal="false"
    @close="handleClose">
    <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入公告标题"></el-input>
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="类型" prop="type">
            <el-select v-model="formData.type" placeholder="请选择公告类型" style="width: 100%">
              <el-option label="通知" value="通知"></el-option>
              <el-option label="维护" value="维护"></el-option>
              <el-option label="活动" value="活动"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="formData.priority" placeholder="请选择优先级" style="width: 100%">
              <el-option label="普通" :value="0"></el-option>
              <el-option label="重要" :value="1"></el-option>
              <el-option label="紧急" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
              <el-option label="草稿" :value="0"></el-option>
              <el-option label="发布" :value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="生效时间" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              type="datetime"
              placeholder="请选择生效时间"
              style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="过期时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="datetime"
              placeholder="请选择过期时间"
              style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="内容" prop="content">
        <el-input
          type="textarea"
          :rows="10"
          placeholder="请输入公告内容"
          v-model="formData.content">
        </el-input>
      </el-form-item>
    </el-form>
    
    <div slot="footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="info" @click="saveDraft">保存草稿</el-button>
      <el-button type="primary" @click="submitForm">发 布</el-button>
    </div>
  </el-dialog>
</template>

<script>
import announcementApi from '@/api/announcement'

export default {
  name: 'AnnouncementForm',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '发布公告'
    },
    announcement: {
      type: Object,
      default: () => ({})
    }
  },
  created() {
    // console.log('原始数据:', this.announcement)  
  },
  data() {
    return {
      dialogVisible: false,
      formData: {
        id: undefined,
        title: '',
        type: '通知',
        priority: 0,
        status: 1,
        startTime: '',
        endTime: '',
        content: '',
        publisherId: 1 // 默认发布者ID
      },
      rules: {
        title: [
          { required: true, message: '请输入公告标题', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择公告类型', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入公告内容', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    },
    announcement: {
      handler(val) {
        if (val) {
          // 无论是否有ID，只要有数据就认为可能是编辑模式
          // console.log('接收到数据:', val)
          
          // 转换数据格式
          const formattedData = this.formatData(val)
          // console.log('格式化后数据:', formattedData)
          
          this.formData = Object.assign({}, this.formData, formattedData)
        } else {
          // 无数据时重置表单
          this.resetForm()
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 格式化数据，确保字段命名符合表单要求
    formatData(data) {
      // 复制原始数据，避免修改源对象
      const formatted = { ...data }
      
      // 打印原始数据的所有字段和对应值，方便调试
      // console.log('原始数据字段:')
      Object.keys(data).forEach(key => {
        console.log(`${key}: ${JSON.stringify(data[key])}`)
      })
      
      // 以下字段我们推测都可能存在
      // 无论字段是否已存在，都尝试从可能的来源获取
      
      // 处理时间字段 - 确保是Date对象
      const processDateField = (value) => {
        if (!value) return ''
        // 如果是字符串，尝试转换为日期对象
        if (typeof value === 'string') {
          try {
            return new Date(value)
          } catch (e) {
            console.error('日期转换失败:', value, e)
            return ''
          }
        }
        return value // 如果已经是Date对象或其他类型，直接返回
      }
      
      // 处理startTime
      if (data.startTime !== undefined) {
        formatted.startTime = processDateField(data.startTime)
      } else if (data.start_time !== undefined) {
        formatted.startTime = processDateField(data.start_time)
      }
      
      // 处理endTime
      if (data.endTime !== undefined) {
        formatted.endTime = processDateField(data.endTime)
      } else if (data.end_time !== undefined) {
        formatted.endTime = processDateField(data.end_time)
      }
      
      // 直接使用已有的驼峰命名字段
      // 下划线命名优先级低于驼峰命名
      if (data.viewCount !== undefined) formatted.viewCount = data.viewCount
      else if (data.view_count !== undefined) formatted.viewCount = data.view_count
      
      if (data.createdAt !== undefined) formatted.createdAt = data.createdAt
      else if (data.created_at !== undefined) formatted.createdAt = data.created_at
      
      if (data.updatedAt !== undefined) formatted.updatedAt = data.updatedAt
      else if (data.updated_at !== undefined) formatted.updatedAt = data.updated_at
      
      if (data.publisherId !== undefined) formatted.publisherId = data.publisherId
      else if (data.publisher_id !== undefined) formatted.publisherId = data.publisher_id
      
      // 处理数字类型字段 - 确保是数字类型
      if (formatted.priority !== undefined && typeof formatted.priority === 'string') {
        formatted.priority = parseInt(formatted.priority, 10)
      }
      
      if (formatted.status !== undefined && typeof formatted.status === 'string') {
        formatted.status = parseInt(formatted.status, 10)
      }
      
      // 打印格式化后的数据
      // console.log('格式化后字段:')
      Object.keys(formatted).forEach(key => {
        console.log(`${key}: ${JSON.stringify(formatted[key])}`)
      })
      
      return formatted
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const formData = Object.assign({}, this.formData)
          formData.status = 1 // 设置为发布状态
          
          // 转换数据为后端需要的格式
          const submitData = this.formatDataForSubmit(formData)
          
          const isEdit = submitData.id !== undefined
          const apiMethod = isEdit ? announcementApi.updateAnnouncement : announcementApi.addAnnouncement
          
          apiMethod(submitData).then(response => {
            if (response.code === 1) {
              this.$message.success(isEdit ? '编辑成功' : '发布成功')
              this.dialogVisible = false
              this.$emit('success')
            } else {
              this.$message.error(response.msg || (isEdit ? '编辑失败' : '发布失败'))
            }
          })
        }
      })
    },
    
    // 保存草稿
    saveDraft() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const formData = Object.assign({}, this.formData)
          formData.status = 0 // 设置为草稿状态
          
          // 转换数据为后端需要的格式
          const submitData = this.formatDataForSubmit(formData)
          
          const isEdit = submitData.id !== undefined
          const apiMethod = isEdit ? announcementApi.updateAnnouncement : announcementApi.addAnnouncement
          
          apiMethod(submitData).then(response => {
            if (response.code === 1) {
              this.$message.success('草稿保存成功')
              this.dialogVisible = false
              this.$emit('success')
            } else {
              this.$message.error(response.msg || '草稿保存失败')
            }
          })
        }
      })
    },
    
    // 格式化提交数据
    formatDataForSubmit(data) {
      const submitData = { ...data }
      
      // 确保适配后端需要的字段格式
      if (submitData.startTime !== undefined) {
        submitData.start_time = submitData.startTime
        // 可以根据需要删除原字段
        // delete submitData.startTime
      }
      
      if (submitData.endTime !== undefined) {
        submitData.end_time = submitData.endTime
        // delete submitData.endTime
      }
      
      if (submitData.publisherId !== undefined) {
        submitData.publisher_id = submitData.publisherId
        // delete submitData.publisherId
      }
      
      return submitData
    },
    
    // 重置表单
    resetForm() {
      this.formData = {
        id: undefined,
        title: '',
        type: '通知',
        priority: 0,
        status: 1,
        startTime: '',
        endTime: '',
        content: '',
        publisherId: 1
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    
    // 关闭对话框
    handleClose() {
      this.resetForm()
    }
  }
}
</script>

<style scoped>

</style> 